package com.itheima.service.db.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.OmsOrder;
import com.itheima.domain.OmsOrderItem;
import com.itheima.domain.OmsOrderOperateHistory;
import com.itheima.mapper.OmsOrderItemMapper;
import com.itheima.mapper.OmsOrderMapper;
import com.itheima.mapper.OmsOrderOperateHistoryMapper;
import com.itheima.service.db.IOrderService;
import com.itheima.vo.OmsOrderVo;
import com.itheima.vo.PageBeanVo;
import com.mysql.jdbc.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author fukeke
 * @since 2022-11-11
 */
@DubboService
public class OrderServiceImpl extends ServiceImpl<OmsOrderMapper, OmsOrder> implements IOrderService {

    @Autowired
    OmsOrderMapper orderMapper;

    @Autowired
    OmsOrderItemMapper omsOrderItemMapper;

    @Autowired
    OmsOrderOperateHistoryMapper oohMapper;

    //分页查询
    @Override
    public PageBeanVo findByPage(Map<String, String> map) throws ParseException {
        //map中参数获取
        //当前页码
        Integer pageNum = Integer.parseInt(map.get("pageNum"));
        //每页条数
        Integer pageSize = Integer.parseInt(map.get("pageSize"));

        IPage<OmsOrder> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<OmsOrder> lqw = new LambdaQueryWrapper<>();

        //提交时间
        if(!StringUtils.isNullOrEmpty(map.get("createTime"))){
            String createTime = map.get("createTime");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format.parse(createTime);
            lqw.between(OmsOrder::getCreateTime, DateUtil.offsetDay(date,0),DateUtil.offsetDay(date,1));
        }

        //订单编号
        if(!StringUtils.isNullOrEmpty(map.get("orderSn"))){
            String orderSn = map.get("orderSn");
            lqw.eq(orderSn != null,OmsOrder::getOrderSn,orderSn);
        }

        //订单类型
        if(!StringUtils.isNullOrEmpty(map.get("orderType"))){
            Integer orderType = Integer.parseInt(map.get("orderType"));
            lqw.eq(orderType != null,OmsOrder::getOrderType,orderType);
        }

        //姓名或号码
        if(!StringUtils.isNullOrEmpty(map.get("receiverKeyword"))){
            String receiverKeyword= map.get("receiverKeyword");
            if(receiverKeyword.charAt(0)=='1'){
                lqw.eq(OmsOrder::getReceiverPhone,receiverKeyword);
            }else {
                lqw.eq(OmsOrder::getReceiverName,receiverKeyword);
            }
        }

        //订单来源
        if(!StringUtils.isNullOrEmpty(map.get("sourceType"))){
            Integer sourceType = Integer.parseInt(map.get("sourceType"));
        lqw.eq(sourceType != null,OmsOrder::getSourceType,sourceType);
        }

        //订单状态
        if(!StringUtils.isNullOrEmpty(map.get("status"))){
            Integer status = Integer.parseInt(map.get("status"));
            lqw.eq(status != null,OmsOrder::getStatus,status);
        }

        lqw.orderByAsc(OmsOrder::getCreateTime);
        //分页查询
        IPage<OmsOrder> omsOrderIPage = orderMapper.selectPage(page, lqw);
        System.out.println(omsOrderIPage.getRecords());
        //创建返回数据对应data
        PageBeanVo pageBeanVo = new PageBeanVo();
        pageBeanVo.setList(omsOrderIPage.getRecords());
        //设置当前页码
        pageBeanVo.setPageNum(pageNum);
        //设置每页条数
        pageBeanVo.setPageSize(pageSize);
        //总记录数
        long count = omsOrderIPage.getTotal();
        pageBeanVo.setTotal(count);
        //总页数
        long totalPage = count % pageSize == 0 ? (count / pageSize) : (count / pageSize) + 1;
        pageBeanVo.setTotalPage(totalPage);
        return pageBeanVo;
    }

    //订单详情
    @Override
    public OmsOrderVo findById(Integer id) {
        //基本信息拷贝到Vo
        OmsOrder omsOrder = orderMapper.selectById(id);
        OmsOrderVo omsOrderVo = new OmsOrderVo();
        BeanUtils.copyProperties(omsOrder,omsOrderVo);
        //封装订单详情集合
        LambdaQueryWrapper<OmsOrderItem> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(OmsOrderItem::getOrderId,id);
        List<OmsOrderItem> orderItemList = omsOrderItemMapper.selectList(lqw1);
        omsOrderVo.setOrderItemList(orderItemList);
        //封装操作历史集合
        LambdaQueryWrapper<OmsOrderOperateHistory> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(OmsOrderOperateHistory::getOrderId,id);
        List<OmsOrderOperateHistory> oohList = oohMapper.selectList(lqw2);
        omsOrderVo.setHistoryList(oohList);
        return omsOrderVo;
    }

    //添加备注
    @Override
    public void note(Long orderId, String note, Integer status) {
        OmsOrderOperateHistory ooh = new OmsOrderOperateHistory();
        ooh.setOrderId(orderId);
        ooh.setNote(note);
        ooh.setOrderStatus(status);
        ooh.setCreateTime(LocalDateTime.now());
        ooh.setOperateMan("后台管理员");
        oohMapper.insert(ooh);
    }

    //批量关闭
    @Override
    public void close(List<Long> list, String note) {
        for (Long orderId : list) {
            OmsOrder order = orderMapper.selectById(orderId);
            order.setStatus(4);
            orderMapper.updateById(order);
            //添加订单操作记录
            OmsOrderOperateHistory ooh = new OmsOrderOperateHistory();
            ooh.setOrderId(orderId);
            ooh.setOrderStatus(4);
            ooh.setOperateMan("后台管理员");
            ooh.setNote(note);
            ooh.setCreateTime(LocalDateTime.now());
            oohMapper.insert(ooh);
        }
    }

    //批量发货
    @Override
    public void delivery(List<HashMap<String,String>> list) {
        for (HashMap<String, String> map : list) {
            //修改订单状态,完善物流信息
            int orderId = Integer.parseInt(map.get("orderId"));
            String deliveryCompany = map.get("deliveryCompany");
            String deliverySn = map.get("deliverySn");
            OmsOrder order = orderMapper.selectById(orderId);
            order.setStatus(2);
            order.setDeliveryCompany(deliveryCompany);
            order.setDeliverySn(deliverySn);
            orderMapper.updateById(order);
            //插入订单操作记录
            OmsOrderOperateHistory ooh = oohMapper.selectById(orderId);
            ooh.setOrderId((long) orderId);
            ooh.setOrderStatus(2);
            ooh.setOperateMan("后台管理员");
            ooh.setNote("完成发货");
            ooh.setCreateTime(LocalDateTime.now());
            oohMapper.insert(ooh);
        }
    }

    //修改收货人信息
    @Override
    public void receiverInfo(HashMap<String, String> map) {
        //修改订单信息
        OmsOrder order = orderMapper.selectById(map.get("orderId"));
        order.setReceiverCity(map.get("receiverCity"));
        order.setReceiverDetailAddress(map.get("receiverDetailAddress"));
        order.setReceiverName(map.get("receiverName"));
        order.setReceiverPhone(map.get("receiverPhone"));
        order.setReceiverPostCode(map.get("receiverPostCode"));
        order.setReceiverProvince(map.get("receiverProvince"));
        order.setReceiverRegion(map.get("receiverRegion"));
        order.setStatus(Integer.parseInt(map.get("status")));
        orderMapper.updateById(order);
        //添加操作记录
        OmsOrderOperateHistory ooh = oohMapper.selectById(map.get("orderId"));
        ooh.setOrderId(Long.parseLong(map.get("orderId")));
        ooh.setOrderStatus(0);
        ooh.setOperateMan("后台管理员");
        ooh.setNote("修改收货人信息");
        ooh.setCreateTime(LocalDateTime.now());
        oohMapper.insert(ooh);
    }

    //删除订单
    @Override
    public void delete(List<Long> ids) {
        for (Long orderId : ids) {
            OmsOrder order = orderMapper.selectById(orderId);
            order.setStatus(5);
            orderMapper.updateById(order);
        }
    }
}
